window.____Xendri = Class({
	initialize: function() {
		$(document.body).addEvent('click', this.____overAllClick);
		document.addEvent('locationChange', this.____onLocationChange);
	},
	____overAllClick: function(evt) {
		var target = evt.target;
		if ($(target).getProperty('ajax')) {
			if ($(target).getProperty('ajax').match('#')) {
				document.location = $(target).getProperty('ajax');
				return;
			}
			if (Xendri.Location.getAnchor()) {
				var link = '#'+Xendri.Location.getAnchor()+'/'+$(target).getProperty('ajax');
			} else {
				var link = '#'+$(target).getProperty('ajax');				
			}
			link = new Xendri.link(link);
			document.location = link.toString(); 
			return;
		}
		var parent = target.parentNode;
		while(parent.getProperty) {
			if ($(parent).getProperty('ajax')) {
				if ($(parent).getProperty('ajax').match('#')) {
					document.location = $(parent).getProperty('ajax');
					return;
				}
				if (Xendri.Location.getAnchor()) {
					document.location = '#'+Xendri.Location.getAnchor()+'/'+$(parent).getProperty('ajax');
				} else {
					document.location = '#'+$(parent).getProperty('ajax');				
				}
				return;
			}
			parent = parent.parentNode;
		}
	},
	____onLocationChange: function() {
		Bro.log('Changing location from '+Xendri.Location.oldLocation+' to '+document.location+'...');
		var link = Xendri.Location.getDiff(document.location+'', Xendri.Location.oldLocation);
		if (!link) {
			if (Xendri.Location.getAnchor()) {
				document.location = Xendri.Location.getAnchor()+'/index@data';
			} else {
				document.location = '#index@data';				
			}
			return;
		}
		$$('body').addClass('wait');
		try {
			Bro.log(link);
			link.follow();
		} catch (e) {
			Bro.log(e);
			$$('//body').removeClass('wait');
			return;
		}
		$$('//body').removeClass('wait');
		Xendri.Location.oldLocation = document.location+'';
	}
});


window.Xendri = {
	// TODO: идентификатор запроса на клиенте обнуляется при каждой перезагрузке страницы. Исправить.
	qcounter: 0,
	nextQueryID: function() {
		if (!this.qcounter) this.qcounter = 0;
		var ret = this.qcounter++;
		return ret;
	},
	JSload: function(file) {
		file = '/index.php?query_id='+Xendri.nextQueryId+'&query_type=js&file='+file;
		loadScript(file);
	}
};

include('lib/xendri2.link.js');
include('lib/xendri2.md5.js');
include('lib/xendri2.location.js');
include('lib/xendri2.json.js');
include('lib/xendri2.popup.js');
include('lib/fx.multi.js');
include('lib/xendri2.rounded.js');
include('lib/xendri2.session.js');
